package com.handong.handserialprogram.module.devicetask;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.ColorContant;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.base.EmergencyActivity;
import com.handong.handserialprogram.module.routemap.RouteMapActivity;
import com.handong.handserialprogram.service.LocateService;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.ViewUtil;




import java.io.File;
import java.util.List;
import android.view.TextureView;

/**
 * 快捷方式创建任务设备列表
 */
public class DeviceTaskActivity extends EmergencyActivity<DeviceTaskPresenter> implements BaseView {

    private static final String TAG = DeviceTaskActivity.class.getSimpleName();
    private String mMissId;
    private String mTaskName;
    private String mTaskTime;
    private MaterialDialog mMissionInfoDialog;

    private FrameLayout mToMapLayout;
    private TextView mStartMission;
    private RecyclerView mDeviceRVList;
    private DeviceListAdapter mListAdapter;
    private LocateService mLocateService;


    private int mMissionStatus = 1;
    private List<FootRingNewEntity> mFootRingNewEntityList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentViewID() {
        return R.layout.activity_device_task;
    }

    @Override
    protected DeviceTaskPresenter createPresenter() {
        return new DeviceTaskPresenter(this);
    }

    @Override
    protected void initViewByID() {
        /**
         * 启动定位SDK并传给串口
         */
        Intent intent = new Intent(this, LocateService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

        mStartMission = (TextView) findViewById(R.id.deviceStartMission);
        mStartMission.setOnClickListener(this);
        mDeviceRVList = (RecyclerView) findViewById(R.id.deviceRecyclerView);
        mToMapLayout = (FrameLayout) findViewById(R.id.deviceToMapLayout);
        mToMapLayout.setOnClickListener(this);
        findView(R.id.headerOptionLayout).setOnClickListener(this);


        ViewUtil.closeDefaultAnimator(mDeviceRVList);
    }



    @Override
    protected void initViewDataRes() {
        initHeaderLayout(false);
        //setOptionOnClick();
        Bundle bundle = getIntent().getExtras();
        if (!bundle.isEmpty()) {
            mTaskName = bundle.getString(KeyConstant.MISSION_NAME);
            mTaskTime = bundle.getString(KeyConstant.MISSION_TIME);
            mMissId = bundle.getString(KeyConstant.MISSION_ID);
            setCenterTitle(mTaskName);
        }
        ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.close_upload_data);
        mPresenter.init();
        mPresenter.beginUploadData(mMissId);//上传数据


    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                finish();
                break;

            case R.id.headerOptionLayout://任务详情
                showTaskInfo();
                break;
            case R.id.deviceStartMission://结束任务
                dealMissionStatusClick();
                break;
            case R.id.deviceToMapLayout://地图查看任务
                Intent intent = new Intent(this, RouteMapActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_bottom_in, R.anim.anim_no);
                break;

            default:
                super.onClick(v);
        }
    }




    /**
     * 显示设备列表
     */
    protected void refreshDeviceList(List<FootRingNewEntity> list) {
        if (mListAdapter == null) {
            mFootRingNewEntityList=list;
            mListAdapter = new DeviceListAdapter(mFootRingNewEntityList, this);
            mDeviceRVList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
            mDeviceRVList.setAdapter(mListAdapter);
        } else {
            mListAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 结束数据上传
     */
    private void dealMissionStatusClick(){
        switch (mMissionStatus){
            case KeyConstant.MISSION_WORKING:
                showStopUploadDialog();
                break;
            case KeyConstant.MISSION_FINISH:
                AppUtil.showShortToast(this, "上传已结束");
                break;
        }
    }
    /**
     * 向指挥中心请求结束任务
     */
    private void showStopUploadDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("温馨提示")
                .content("是否向指挥中心请求结束任务？")
                .positiveText(R.string.dialog_positive_text)
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.bg_gray)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mPresenter.queryMissionState();
                    }
                }).build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 休眠脚环失败
     */
    protected void logoutFootRingError(final String id) {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .content("休眠脚环失败")
                .negativeColorRes(R.color.dialog_bg)
                .negativeText("直接退出")
                .positiveText(R.string.dialog_positive_again)
                .positiveColorRes(R.color.back_ground_green)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.logoutSuccess();
                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.logoutAllFootRing();
                    }
                }).build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * sim卡错误
     */
    protected void simInitErrorMissOpen(String missID) {
        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_problem)
                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请结束任务重新检查！")
                .positiveText(R.string.close_upload_data)
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.requestStopMiss();
                    }
                }).build());
    }

    /**
     * 服务器同意结束任务
     */
    public void showResponseSuccessDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_request_success)
                .content("指挥中心已同意结束任务，是否结束任务并注销脚环?")
                .positiveColorRes(R.color.back_ground_green)
                .canceledOnTouchOutside(false)
                .positiveText("立即结束")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mPresenter.stopUploadData();
                        mMissionStatus = KeyConstant.MISSION_FINISH;
                        ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.stopped_upload_data);
                    }
                })
                .build();
        ViewUtil.removeAllKeyListener(dialog);
    }

    /**
     * 服务器结束任务
     */
    public void showMissionOverDialog() {
        Intent intent = new Intent(this, DeviceTaskActivity.class);
        startActivity(intent);
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_careful)
                .content("指挥中心发出结束任务命令，是否立即执行并注销脚环?")
                .positiveColorRes(R.color.back_ground_green)
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_now_execute)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mPresenter.stopUploadData();
                        mMissionStatus = KeyConstant.MISSION_FINISH;
                        ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.stopped_upload_data);
                    }
                })
                .build();
        ViewUtil.removeAllKeyListener(dialog);
    }

    /**
     * 结束任务超时
     */
    public void showFinMissTimeOutDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_request_fail)
                .content("指挥中心无回复，请通过其他方式联系！")
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText(R.string.dialog_positive_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 指挥中心拒绝
     */
    public void showServerRejectDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_request_reject)
                .content("指挥中心不允许结束任务，请继续执行！")
                .positiveColorRes(R.color.back_ground_green)
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 发送失败检查网络
     */
    public void showSendErrorDialog() {
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_request_fail)
                .content("无法发出结束请求，请检查本机网络！")
                .positiveColorRes(R.color.back_ground_green)
                .canceledOnTouchOutside(false)
                .positiveText(R.string.dialog_positive_text)
                .build();
        ViewUtil.removeHomeKeyListener(dialog);
    }

    /**
     * 查看任务详情
     */
    private void showTaskInfo() {
        if (mMissionInfoDialog == null) {
            View customView = LayoutInflater.from(this).inflate(R.layout.dialog_single_task_info, null, false);
            TextView reason = (TextView) customView.findViewById(R.id.taskInfoReason);
            TextView startPlace = (TextView) customView.findViewById(R.id.taskInfoStartPlace);
            TextView devices = (TextView) customView.findViewById(R.id.taskInfoDevices);
            //TextView hospital = (TextView) customView.findViewById(R.id.taskInfoHospital);
            TextView executeCar = (TextView) customView.findViewById(R.id.taskInfoExecuteCar);
            //TextView otherPerson = (TextView) customView.findViewById(R.id.taskInfoDoctor);
            //TextView moreInfo = (TextView) customView.findViewById(R.id.taskInfoMore);

            reason.setText(mTaskName);
            devices.setText(SPUtil.getStringValue(SPUtil.PHONE_NAME));
            //hospital.setText(mEntity.getTaskEndPlace());
            startPlace.setText(mTaskTime);
            executeCar.setText("暂无");

            mMissionInfoDialog = new MaterialDialog.Builder(this)
                    .title("任务详情")
                    .customView(customView, true)
                    .positiveText("了解")
                    .positiveColorRes(R.color.btn_green_bg)
                    .build();
        }
        ViewUtil.removeHomeKeyListener(mMissionInfoDialog);
    }


    protected boolean isMissionExecuting(){
        return mMissionStatus == KeyConstant.MISSION_WORKING;
    }

    /**
     * 任务已结束设置状态
     */
    protected void missionIsFinished(){
        showLoadDialog("任务已结束，脚环休眠中...");
        mMissionStatus = KeyConstant.MISSION_FINISH;
        ViewUtil.changeBtnStatus(mStartMission, ColorContant.MISSION_NORMAL, R.string.stopped_upload_data);
    }
    /**
     * 结束任务后才能退出
     * @return
     */
    @Override
    public void finish() {
        if (mPresenter.isStopExit()){
            return;
        }
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    /**
     * 休眠脚环
     */
    protected void showExitDialog() {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("请休眠脚环后，再退出？")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutAllFootRing();

                    }
                }).build());
    }

    @Override
    protected void onDestroy() {
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
            mServiceConnection = null;
        }
        super.onDestroy();
    }
    /**
     * 定位服务
     */
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocateService.LocateBinder binder = (LocateService.LocateBinder) service;
            mLocateService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mLocateService = null;
        }
    };
}
